package cn.itsource.pethome.service.impl;

import cn.itsource.pethome.mapper.BaseMapper;
import cn.itsource.pethome.query.BaseQuery;
import cn.itsource.pethome.service.IBaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.List;

/**
 * service层父接口的实现类，也是其他实现类的父类
 * @param <T>
 * @param <Q>
 */
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T, Q extends BaseQuery> implements IBaseService<T, Q> {

    @Autowired
    private BaseMapper<T, Q> baseMapper;

    @Override
    @Transactional
    public void save(T t) {
        try {
            Class<?> clz = t.getClass();
            Field idField = clz.getDeclaredField("id");     //获取id字段  上次是获取的getId方法
            idField.setAccessible(true);    //允许访问私有的成员变量
            Object idValue = idField.get(t);//获取id字段的值
            if(idValue == null){
                baseMapper.save(t);
            }else{
                baseMapper.update(t);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        baseMapper.delete(id);
    }

    @Override
    @Transactional
    public void batchRemove(List<Long> ids) {
        baseMapper.batchRemove(ids);
    }

    @Override
    public T findOne(Long id) {
        return baseMapper.findOne(id);
    }

    @Override
    public PageInfo<T> findPage(Q q) {
        //使用PageHelper来实现分页查询
        PageHelper.startPage(q.getPageNo(), q.getPageSize());
        List<T> list = baseMapper.findAll(q);
        return new PageInfo<T>(list);
    }

}
